package net.chengp.ms.auth.service;

import java.util.Arrays;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import lombok.extern.slf4j.Slf4j;

/**
 * 用户管理
 * @author chengp
 *
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

	private static final Cache<String, UserDetails> userCache = CacheBuilder.newBuilder().maximumSize(Integer.MAX_VALUE)
			.expireAfterAccess(10, TimeUnit.SECONDS).build();

	@Autowired
	private PasswordEncoder passwordEncoder;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		return getUserDetails(username);
	}

	private UserDetails getUserDetails(String username) {
		try {
			return userCache.get(username, new Callable<UserDetails>() {
				@Override
				public UserDetails call() throws Exception {
					// TODO 这里需要从数据库查询用户
					return new UserDetails("chengp", passwordEncoder.encode("123456"), Arrays.asList("ADMIN"));
				}
			});
		} catch (Exception e) {
			log.error("查询用户失败!", e);
		}
		return null;
	}

}
